package com.itheima.reggie.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品（携带口味信息）
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishDto) {
        log.info("新增菜品");
        log.info(dishDto.toString());
        //新增菜品：保存菜品基本信息+保存菜品的口味信息
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功！");
    }

    /**
     * 分页查询菜品
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        log.info("菜品分页查询");
        //创建page对象，设置当前页和每页大小
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        //封装查询条件 select * from Dish like ‘%%’
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //封装排序
        qw.orderByDesc(Dish::getUpdateTime);
        //开始查询
        dishService.page(pageInfo, qw);
        Map map = new HashMap<>();
        //总条目数
        int total = (int) pageInfo.getTotal();//注意long会自动转成字符串
        map.put("total", total);
        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        // records: List<Dish>  从页面查看，发现需要category_Name,
        //但Dish中没有，需要新建一个类(DishDto 之前建过了)去接收category_Name
        // 只有菜品分类id：categoryId，没有分类名称
        // 根据菜品分类id，查询菜品分类数据。再set进去
        List<DishDto> dishdtos = new ArrayList<>();
        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            //根据分类id拿到分类对象
            Category category = categoryService.getById(categoryId);
            //再依据分类对象拿到分类名
            String categoryName = category.getName();
            //将分类名set到dishDto中
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(categoryName);
            //再将Dish中的数据放到DishDto中 Copy
            dishdtos.add(dishDto);
        }
        // List<Dish> records ---> List<DishDto> dishDtos
        // for循环的写法：
        map.put("records", dishdtos);
        return R.success(map);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        log.info("根据id查询菜品数据,用于回显");

        DishDto dishDto = new DishDto();
        //查询菜品数据,copy给dishDto
        Dish dish = dishService.getById(id);
        BeanUtil.copyProperties(dish,dishDto);

        //查询菜品的口味数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(lqw);

        //设置dishDto的口味数据
        dishDto.setFlavors(list);

        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * （不仅要修改菜品基本信息，还要修改口味数据）
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        log.info("修改菜品数据");
        //存储数据到dish表
        dishService.updateById(dishDto);
        //获取菜品id
        Long id = dishDto.getId();
        //根据菜品id删除flavor表中的数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(lqw);
        //存储数据到dishFlavor表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置flavor表中的菜品id
            flavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功");
    }

    /**
     * 逻辑删除菜品(根据id删除/批量删除）
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids) {
        log.info("根据id删除");
        //删除菜品口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(wrapper);
        //遍历需要删除的菜品id
        for (Long id : ids) {
            //根据菜品的id知道菜品分类的id
            Long categoryId = dishService.getById(id).getCategoryId();
            //如果是套餐，则不能删除
            if (categoryService.getById(categoryId).getType() != 1) {
                return R.error("当前菜品关联了套餐,不能删除!");
            }
        }
        dishService.removeByIds(ids);
       return R.success("删除成功");
    }

    /**
    * （批量）停售/起售
     *
     * @param status
     * @param ids
     * @return
     */
   @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,
                                  @RequestParam List<Long> ids) {
        log.info("设置菜品状态");
        log.info(status.toString());
        //设置条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Dish::getId, ids);
        lqw.orderByDesc(Dish::getPrice);

        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("操作成功");
    }
    /**
     * 根据分类id查询所有菜品集合(增加菜品口味数据)
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getDish(Long categoryId,Integer status){
        log.info("根据分类id查询所有菜品集合");
        //根据分类id查询所有菜品集合
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,categoryId).eq(Dish::getStatus ,status);
        List<Dish> dishList = dishService.list(lqw);

        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //将dish属性属性据拷贝给dishDto
            BeanUtil.copyProperties(dish,dishDto);
            //查询dish相关的口味信息
            LambdaUpdateWrapper<DishFlavor> lqw2 = new LambdaUpdateWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw2);
            //将dish相关的口味信息设置给dishDto
            dishDto.setFlavors(dishFlavors);
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }
}
